<?php

namespace app\home\controller;

use app\common\controller\Home;
use think\Controller;
use think\Cookie;
use think\Db;

class Index extends Home
{
    protected $NoLoginUser = ['login', 'register', 'logout', 'index'];

    public function __construct()
    {


        //继承父级的构造函数
        parent::__construct();

        //引用用户模型
        $this->UserModel = model('User.User');

        //引用分类模型
        $this->CateModel = model('Cate');

        //引用帖子模型
        $this->PostModel = model('Post.Post');

        //引用签到模型
        $this->SignModel = model('Sign');

        $this->CommentModel = model('Post.Comment');
    }

    //前台首页
    public function index()
    {
        //接收到分类id
        $cateid = $this->request->param('cateid', 0);

        //是否采纳
        $accept = $this->request->param('accept', '');

        //接收搜索的参数
        $keyword = $this->request->param('keyword', '');

        $state = $this->request->param('state', '');

        //定义一个条件数组
        $where = [];

        //分类id是否不为空
        if ($cateid) {
            $where['cateid'] = $cateid;
        }

        //采纳不为空
        if ($accept != '') {
            if ($accept == 0) {
                //未结
                $where['accept'] = ['exp', Db::raw('is null')];
            } elseif ($accept == 1) {
                $where['accept'] = ['exp', Db::raw('is not null')];
            }
        }

        //搜索
        if ($keyword) {
            $where['title|post.content'] = ['like', "%$keyword%"];
        }

        //判断点击的是精华还是热门
        if ($state) {
            $where['state'] = $state;
        }

        //查询分类数据
        $CateList = $this->CateModel->order('weigh', 'asc')->select();

        //查询帖子表里面的数据
        $PostList = $this->PostModel->with(['user', 'cate'])->where($where)->order('createtime', 'desc')->paginate(10);

        //置顶的数据
        $ToppList = $this->PostModel->with(['user', 'cate'])->where('state', 1)->order('createtime', 'desc')->paginate(10);

        //置顶帖子的总数
        $total = $ToppList->total();

        //判断今天是否签到
        $LoginUser = Cookie::get('LoginUser');
        $todayBegin = date('Y-m-d' . " 00:00:00"); //开始时间
        $todayEnd = date('Y-m-d' . " 23:59:59"); //结束时间
        $SignList = $this->SignModel->where(['userid' => $LoginUser['id']])->find(); //根据id查询出签到表的数据
        $Signing = $this->SignModel->field('times')->where(['userid' => $LoginUser['id']])->where('times', 'between', [$todayBegin, $todayEnd])->find();

        //模板赋值
        $this->assign([
            'CateList' => $CateList,
            'PostList' => $PostList,
            'ToppList' => $ToppList,
            'total' => $total,
            'cateid' => $cateid,
            'accept' => $accept,
            'state' => $state,
            'SignList' => $SignList,
            'Signing' => $Signing
        ]);


        return $this->fetch();
    }

    //注册
    public function register()
    {
        $LoginUser = Cookie::get('LoginUser');

        //cookie不为空时就去数据表查有没有这个用户
        if (!empty($LoginUser)) {
            //获取到cookie里的id
            $id = isset($LoginUser['id']) ? $LoginUser['id'] : '0';

            //根据id去查询用户表是否有该用户
            $User = $this->UserModel->find($id);

            //能在数据表查询到该用户 说明用户已经注册过
            if ($User) {
                //要么返回个人中心或者首页
                $this->success('你已经注册,无需重复注册', url('home/user/index'));
            }
        }

        //判断表单是否有数据提交
        if ($this->request->isPost()) {
            //接受验证码
            $vercode = $this->request->param('vercode', '');

            //验证码 如果false就执行if里面的代码
            if (!captcha_check($vercode)) {
                $this->error('验证码错误');
                exit;
            }
            $params = $this->request->param();

            //repass 确认密码 pass密码
            if ($params['pass'] != $params['repass']) {
                $this->error('密码不一致,请重新输入');
                exit;
            }

            // 密码盐
            $salt = build_ranstr(10);

            // 密码加上密码盐 然后md5
            $password = md5($params['pass'] . $salt);
            // 查询配置表,获取注册后会有的积分
            $RegisterPoint = model('Config')->where(['key' => 'RegisterPoint'])->value('value');
            // SELECT `value` FROM `pre_config` WHERE ( `key` = 'RegisterPoint' ) AND `pre_config`.`deletetime` IS NULL LIMIT 1

            $RegisterPoint = is_numeric($RegisterPoint) ? abs($RegisterPoint) : '';

            // 封装一个数据数组
            $data = [
                'email' => $params['email'],
                'password' => $password,
                'nickname' => $params['nickname'],
                'salt' => $salt,
                'sex' => 0,
                'vip' => 0,
                'auth' => 0,
                'point' => $RegisterPoint,
            ];

            $result = $this->UserModel->validate('common/User/User')->save($data);

            if ($result === FALSE) {
                $this->error($this->UserModel->getError());
                exit;
            } else {
                $this->success('注册成功', url('home/index/login'));
                exit;
            }
        }

        return $this->fetch();
    }

    //登录
    public function login()
    { // 获取到cookie
        $LoginUser = Cookie::get('LoginUser');

        // 如果cookie不为空
        if (!empty($LoginUser)) {
            $id = isset($LoginUser['id']) ? $LoginUser['id'] : 0;

            $User = $this->UserModel->find($id);

            if ($User) {
                // 要么返回个人中心或者首页
                $this->success('你已登录，无须重复登录', url('home/user/index'));
                exit;
            }
        }

        // 判断是否有POST提交的数据
        if ($this->request->isPost()) {
            // 获取验证码
            $vercode = $this->request->param('vercode', '');

            if (!captcha_check($vercode)) {
                $this->error('验证码错误，请重新输入');
                exit;
            }

            // 接收email
            $email = $this->request->param('email');

            // 密码
            $pass = $this->request->param('pass');

            $User = $this->UserModel->where('email', $email)->find();

            if (!$User) {
                $this->error('你输入的邮箱错误或未注册，请检查是否正确');
                exit;
            }

            $salt = $User['salt'];

            $password = md5($pass . $salt);

            if ($User['password'] != $password) {
                $this->error('密码错误，请重新输入');
                exit;
            }

            // 封装一个cookie数据
            $data = [
                'id' => $User['id'],
                'email' => $User['email'],
                'nickname' => $User['nickname'],
                'vip' => $User['vip'],
                'auth' => $User['auth'],
                'avatar' => is_file($User['avatar']) ? $User['avatar'] : '/static/home/res/images/avatar.jpg',
                'cover' => is_file($User['cover']) ? $User['cover'] : '/static/home/res/images/back.jpg'
            ];

            // 设置cookie
            Cookie::set('LoginUser', $data);

            $this->success('登录成功', url('home/user/index'));
            exit;
        }
        return $this->fetch();
    }

    //用户验证邮箱
    public function email()
    {
        //接受到参数  $auth:md5加密后的邮箱值
        $auth = $this->request->param('email', '');

        //查询所有的邮箱以及id
        $UserList = $this->UserModel->field('id,email')->select();

        //用户id
        $Userid = 0;

        //循环UserList
        foreach ($UserList as $v) {

            //把查询出来的用户邮箱全部md5加密
            $email = md5($v['email']);

            //如果通过参数传过来的邮箱值跟循环的相等,就说明邮箱匹配
            if ($auth == $email) {
                //赋值
                $Userid = $v['id'];
                break;
            }
        }

        //判断是否拿到用户id
        if (!$Userid) {
            $this->error('未找到该邮箱,请确认邮箱是否正确', url('home/user/profile'));
        }

        //封装更新认证的数据
        $data = [
            'id' => $Userid,
            'auth' => 1
        ];

        $result = $this->UserModel->isUpdate(true)->save($data);

        if ($result === FALSE) {
            $this->error('认证失败,请检查邮箱是否正确', url('home/user/profile'));
            exit;
        } else {
            $this->success('认证成功', url('home/user/profile'));
            exit;
        }
    }

    //退出登录
    public function logout()
    {
        Cookie::delete('LoginUser');
        $this->success('退出成功', url('home/index/login'));
        exit;
    }

    //签到
    public function signin()
    {
        if ($this->request->isAjax()) {
            //用户id
            $userid = $this->request->param('userid', '');

            if ($userid) {
                $data = $this->SignModel->where('userid', $userid)->find();

                //判断该用户有没有签到记录
                if (!$data) {
                    //首次签到
                    $data = [
                        'times' => date('Y-m-d H:i:s'),
                        'userid' => $userid,
                        'days' => 1,
                        'number' => 5,
                        'one' => date('d', time())
                    ];
                    $query = $this->SignModel->save($data);

                    if ($query) {
                        $this->finish('签到成功');
                    } else {
                        $this->error('签到失败');
                    }
                } else {
                    //今日未签到
                    $time = strtotime($data['times']);

                    if ((time() - $time) > 24 * 60 * 60) {
                        //上次签到时间大于24小时,连续签到天数清零
                        $query = $this->SignModel->where(['userid' => $userid])->update(['days' => 1]);
                    } else {
                        //上次签到时间小于24小时,连续签到天数加一
                        $query = $this->SignModel->where(['userid' => $userid])->setInc('days');
                    }

                    //更新上次签到时间和签到积分
                    $query1 = $this->SignModel->where(['userid' => $userid])->update(['times' => date('Y-m-d H:i:s')]);
                    $query2 = $this->SignModel->where(['userid' => $userid])->setInc('number', 5);

                    //将积分添加到用户表的积分中
                    $query3 = $this->UserModel->where(['id' => $userid])->setInc('point', 5);

                    if ($query1 === FALSE || $query2 === FALSE) {
                        $this->error('签到失败');
                    } else {
                        $this->finish('签到成功');
                    }
                }
            }
        }
    }

    //帖子详细界面
    public function info()
    {
        $postid = $this->request->param('postid', 0);

        //获取点击分类的id
        $cateid = $this->request->param('cateid', 0);
        $accept = $this->request->param('accept', '');

        //查询帖子信息 
        $post = $this->PostModel->with(['cate', 'user'])->find($postid);

        if (!$post) {
            $this->error('悬赏帖子未找到，请重新选择', url('home/index/index'));
            exit;
        }

        //查询评论总数
        $count = $this->CommentModel->where(['postid' => $postid])->count();


        //访问量 字符串变成数组
        $visit = trim($post['visit']);
        $VisitArr = explode(',', $visit); //转换为数组
        $VisitArr = array_filter($VisitArr);  //去除数组中的空元素
        $VisitCount = is_array($VisitArr) ? count($VisitArr) : 0;

        //判断是否有登录
        $User = empty(Cookie::get('LoginUser')) ? [] : Cookie::get('LoginUser');
        $userid = isset($User['id']) ? $User['id'] : 0;
        $User = $this->UserModel->find($userid);

        //收藏的状态
        $CollectStatus = false;

        if ($User) {
            $collect = model('User.Collect')->where(['userid' => $User['id'], 'postid' => $postid])->find();

            //如果查出来有，说明有收藏
            $CollectStatus = $collect ? true : false;


            //判断这个人是否访问过，没有访问过，要加上去这个人ID 就代表访问过了

            //当前这个人没访问过
            if (!in_array($User['id'], $VisitArr)) {
                $VisitArr[] = $User['id'];

                //组装数据   
                $data = [
                    'id' => $post['id'], //一定要有id
                    'visit' => implode(',', $VisitArr)   //数组转化为字符串
                ];

                //更新语句
                $this->PostModel->isUpdate(true)->save($data);
            }
        }

        //查询评论
        $commentlist = $this->CommentModel->with(['user'])
            ->where(['postid' => $postid])
            ->order('id', 'asc')
            ->order('level', 'asc')
            ->select();

        //将评论递归处理
        $commentlist = CommentTree($commentlist, 0, $User);

        // var_dump(collection($commentlist)->toArray());
        // exit;


        //查询分类列表
        $catelist = model('Post.Cate')->order('weigh', 'asc')->limit(6)->select();

        $this->assign([
            'cateid' => $cateid,
            'accept' => $accept,
            'catelist' => $catelist,
            'post' => $post,
            'CollectStatus' => $CollectStatus,
            'count' => $count, //评论数
            'VisitCount' => $VisitCount, //访问量
            'commentlist' => $commentlist, //评论列表
        ]);

        //渲染模板
        return $this->fetch();
    }
}
